<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="1000px"
      @close="cancelSubmit"
    >
      <div class="content">
        <div class="content-left">
          <div class="search-wrap">
            <el-form :model="form" :inline="true" ref="form" label-width="40px">
              <el-form-item label="学校">
                <el-select
                  v-model="form.schoolId"
                  placeholder="请选择学校"
                  @change="schoolChange"
                >
                  <el-option
                    v-for="school in schoolList"
                    :key="school.schoolId"
                    :label="school.schoolName"
                    :value="school.schoolId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="姓名">
                <el-input
                  @change="nameChange"
                  v-model.trim="form.name"
                  placeholder="请输入姓名"
                  clearable
                ></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="tree-wrap">
            <el-tree
              :data="treedata"
              show-checkbox
              default-expand-all
              node-key="nodeId"
              ref="tree"
              highlight-current
              :filter-node-method="filterNode"
              :check-on-click-node="true"
              :expand-on-click-node="false"
              @check="treeCheckChange"
              :props="defaultProps"
              :render-content="renderContent"
            >
            </el-tree>
          </div>
        </div>
        <div class="content-center">
          <!-- <i class="el-icon-d-arrow-right" @click="selectNode"></i> -->
        </div>
        <div class="content-right">
          <div class="add-num">{{ `已添加${selectNodes.length}` }}</div>
          <div v-if="selectNodes.length === 0">
            <el-empty description="暂无数据"></el-empty>
          </div>
          <div
            v-else
            v-for="node in selectNodes"
            :key="node.id + Math.random()"
            class="select-item"
          >
            <!-- <span :title="`${node.name}(${node.account})【${node.className}】【${node.parentName}】`">{{
              `${node.name}(${node.account})【${node.className}】【${node.parentName}】`
            }}</span> -->
            <span :title="node.name" class="name">{{
              handleName(node.name)
            }}</span>
            <span :title="node.account" class="account">{{
              `(${handleAccount(node.account)})`
            }}</span>
            <span :title="node.className" class="className">{{
              handleClassName(node.className)
            }}</span>
            <span :title="node.parentName" class="parentName">{{
              handleClassName(node.parentName)
            }}</span>
            <i class="el-icon-close" @click="deleteNode(node)"></i>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="cancelSubmit">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash';
import {
  getClassStudentLists,
  getSchoolTree,
  updateGroupStudent,
  getAllOpenSchoolList,
} from '@/api/setClass.js';
const DEFAULT_LEVEL = 3;
export default {
  data() {
    return {
      name: 'ljq',
      visible: false,
      form: {
        schoolId: '',
        name: '',
      },
      schoolList: [],
      // 树的数据数组
      treedata: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      selectNodes: [],
      selectNodesMap: new Map(),
      initTreeFlag: false,
    };
  },
  props: {
    title: {
      type: String,
      default: '添加学生',
    },
    classId: {
      type: [String, Number],
      default: '',
    },
    schoolId: [String, Number],
  },
  computed: {
    selectNodesIds() {
      console.log(
        'selectNodesIds',
        this.selectNodes.map((item) => {
          return `${DEFAULT_LEVEL}_${item.id}`;
        })
      );
      return this.selectNodes.map((item) => {
        return `${DEFAULT_LEVEL}_${item.id}`;
      });
    },
    canSetTree() {
      return {
        selectNodesIds: this.selectNodesIds,
        initTreeFlag: this.initTreeFlag,
      };
    },
  },
  watch: {
    canSetTree() {
      console.log('canSetTree', this.canSetTree, this.selectNodesIds);
      // 初始化数据才去调用该api
      if (this.initTreeFlag && this.selectNodesIds.length) {
        setTimeout(() => {
          this.$refs.tree &&
            this.$refs.tree.setCheckedKeys(this.selectNodesIds);
          this.initTreeFlag = false;
        }, 8);
      }
    },
  },
  methods: {
    handleName(name) {
      if (name.length > 4) {
        return name.slice(0, 4) + '...';
      }
      return name;
    },
    handleAccount(name) {
      if (name.length > 7) {
        return name.slice(0, 3) + '*' + name.slice(name.length - 3);
      }
      return name;
    },
    handleClassName(name) {
      if (name.length > 6) {
        return name.slice(0, 4) + '...';
      }
      return name;
    },
    renderContent(h, { node, data, store }) {
      if (data.level == 3) {
        console.log('renderContent', node, data);
        return (
          <span class="custom-tree-node">
            <span>{node.label + '(' + data.account + ')'}</span>
          </span>
        );
      }
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
        </span>
      );
    },
    // 取消提交
    cancelSubmit() {
      this.treedata = [];
      this.selectNodesMap.clear();
      this.selectNodes = [];
      this.visible = false;
      this.$refs.tree.setCheckedKeys([]);
    },
    submit() {
      let params = {
        schoolId: this.schoolId,
        initGrade: this.initGrade,
        classId: this.classId,
        studentIdList: this.selectNodes.map((item) => item.id),
      };
      // if (this.selectNodesIds.length === 0) {
      //   return this.$message.info("请先选择学生！");
      // }
      updateGroupStudent(params).then((res) => {
        if (res[1] && res[1].code == 0) {
          this.$message.success('保存成功');
          setTimeout(() => {
            this.$emit('refreshList');
            this.cancelSubmit();
          }, 1500);
        } else {
          // this.$message.info(res[1].msg);
        }
      });
    },
    // 学校选择改变
    schoolChange(value) {
      this.init(value, false);
    },
    // 名字改变
    nameChange(val) {
      this.$refs.tree.filter(val);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.level === DEFAULT_LEVEL && data.name.indexOf(value) !== -1;
    },
    // 初始化树节点列表
    init(initSchoolId, first = true) {
      console.log('initSchoolId', initSchoolId);
      // 清空搜索框，获取树的数据，以及已选择列表等操作 todo
      this.form.name = this.$options.data().form.name;
      let params = {
        schoolId: initSchoolId,
        layer: DEFAULT_LEVEL,
        classType: 'normal',
      };
      if (first) {
        getAllOpenSchoolList({}).then((res) => {
          if (res[1] && res[1].code == 0) {
            this.schoolList = res[1].data || [];
            if (this.schoolList.length === 0) {
              this.$message.info('学校列表为空，无法选择学生');
              this.cancelSubmit();
            }
          } else {
            this.$message.info('学校列表异常，无法选择学生');
            this.cancelSubmit();
          }
          this.form.schoolId = initSchoolId;
        });
        getClassStudentLists({
          classId: this.classId,
        }).then((res) => {
          if (res[1] && res[1].code == 0) {
            let nodes = (res[1].data.studentList || []).map((item) => {
              return {
                id: item.studentId,
                name: item.studentName,
                parentId: item.schoolId,
                className: item.className,
                parentName: item.schoolName,
                account: item.userName,
              };
            });
            // 根据age属性将arr数组分组
            const groupedArr = Object.values(
              nodes.reduce((acc, obj) => {
                const key = obj.parentId; // 选取要分组的属性值作为key
                if (!acc[key]) {
                  acc[key] = []; // 如果该key不存在于结果中，则创建新的空数组
                }
                acc[key].push(obj); // 将当前元素添加到相应的group中
                return acc;
              }, {})
            );
            groupedArr.forEach((item) => {
              let schoolId = item[0].parentId;
              this.updateNodes(item, schoolId);
            });
          } else {
            // this.$message.info(res[1].msg);
          }
        });
      }
      // 获取学校数据
      getSchoolTree(params).then((res) => {
        if (res[1] && res[1].code == 0) {
          // const showData = this.filterNotChildNodes(res[1].data.gradeList || []); // todo
          // console.log('showData:', showData);
          this.initTreeFlag = true;
          this.treedata = res[1].data.gradeList || [];
          this.visible = true;
        } else {
          // this.$message.info(res[1].msg);
        }
      });
    },
    filterNotChildNodes(treeData) {
      function eachItem(arr) {
        let res = arr.filter((item) => {
          if (item.children && item.children.length > 0) {
            item.children = eachItem(item.children);
          }
          return item.children.length;
        });
        return res.length ? res : [];
      }
      return eachItem(treeData);
    },
    treeCheckChange(data, obj) {
      console.log('check-change', data, obj);
      let selectNodes = obj.checkedNodes.filter(
        (item) => item.level === DEFAULT_LEVEL
      );
      selectNodes.forEach((node) => {
        // 获取父亲节点，爷爷节点
        let treeNode = this.$refs.tree.getNode(node);
        let classData = treeNode.parent.data;
        let grade = treeNode.parent.parent.data;
        node.className = classData.name;
        node.parentName = this.getSchoolName(this.form.schoolId);
        node.parentId = this.form.schoolId;
      });
      this.updateNodes(selectNodes, this.form.schoolId);
      // this.selectNodes = _.unionBy(selectNodes, this.selectNodes, 'id');
    },
    getSchoolName(schoolId) {
      let schoolName = '';
      this.schoolList.forEach((item) => {
        if (item.schoolId == schoolId) {
          schoolName = item.schoolName;
        }
      });
      return schoolName;
    },
    updateNodes(selectNodes, schoolId) {
      console.log('updateNodes', selectNodes, schoolId);
      this.selectNodesMap.set(schoolId, selectNodes);
      let nodes = [];
      for (let value of this.selectNodesMap.values()) {
        nodes = nodes.concat(value);
      }
      this.selectNodes = nodes;
    },
    deleteNode(node) {
      let nodeSchoolId = node.parentId;
      // 删除node
      this.$refs.tree.setChecked(node, false);
      let nodes = this.selectNodesMap.get(nodeSchoolId);
      nodes = nodes.filter((item) => {
        return item.id !== node.id;
      });
      this.updateNodes(nodes, nodeSchoolId);
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  height: 500px;
  &-left {
    margin: 10px;
    flex-basis: 58%;
    width: 58%;
    .tree-wrap {
      overflow: auto;
      height: calc(100% - 60px);
    }
  }
  &-center {
    flex-basis: 0%;
    display: flex;
    align-content: space-around;
    justify-content: space-around;
    align-items: center;
    i {
      cursor: pointer;
    }
  }
  &-right {
    margin: 10px;
    flex-basis: 40%;
    width: 40%;
    overflow: auto;
    .add-num {
      height: 36px;
      line-height: 36px;
      font-weight: 500;
    }
    .select-item {
      height: 36px;
      line-height: 36px;
      span {
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      span.name {
        width: 20%;
      }

      span.account {
        width: 20%;
      }

      span.parentName {
        width: 24%;
      }

      span.className {
        width: 24%;
      }
      i {
        cursor: pointer;
        margin: 10px 0;
        vertical-align: top;
      }
    }
  }
}
</style>
